﻿import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exercise_recording_state.dart';
import '../../../../common/model/exercise_type.dart';
import '../../../../services/ring_service.dart';
import '../../../../core/controllers/ring_controller.dart';
import '../routes.dart';

/// GPS运动记录控制器
class ExerciseRecordingLogic extends GetxController {
  final ExerciseRecordingState state = ExerciseRecordingState();
  final RingService _ringService = Get.find<RingService>();
  final RingController _ringController = Get.find<RingController>();
  
  Timer? _gpsTimer;
  Timer? _recordingTimer;
  ExerciseType? exerciseType;
  String? currentTrainingType; // 当前训练类型（SDK返回的类型）
  
  // 锻炼列表数据
  final RxList<Map<String, dynamic>> exerciseList = <Map<String, dynamic>>[].obs;
  final RxBool isLoadingExerciseList = false.obs;

  @override
  void onInit() {
    super.onInit();
    // 获取传入的运动类型
    final arguments = Get.arguments as Map<String, dynamic>?;
    exerciseType = arguments?['exerciseType'] as ExerciseType?;
    
    // 开始GPS信号检测
    _startGpsSignalDetection();
    
    // 加载锻炼列表
    loadExerciseList();
    
    // 倒计时结束后进入页面，但不自动开始记录
    // 用户需要手动点击"开始"按钮才开始记录
  }
  
  /// 加载锻炼列表（从SDK获取）
  Future<void> loadExerciseList() async {
    try {
      isLoadingExerciseList.value = true;
      
      // 检查设备是否连接
      if (!_ringController.isConnected) {
        Toast.show('设备未连接');
        return;
      }
      
      // 调用RingController查询历史训练数据
      await _ringController.queryHistoryTraining();
      
      // 监听RingService返回的数据
      ever(_ringService.historyTrainingListRx, (list) {
        exerciseList.value = list;
        if (list.isNotEmpty) {
          Toast.show('加载了 ${list.length} 条锻炼记录');
        }
      });
    } catch (e) {
      Toast.show('加载锻炼列表失败: $e');
    } finally {
      isLoadingExerciseList.value = false;
    }
  }
  
  /// 查看锻炼详情（从SDK获取详细数据）
  Future<void> viewExerciseDetail(Map<String, dynamic> exerciseData) async {
    try {
      // 获取训练记录的ID
      final id = exerciseData['id'] as int?;
      
      if (id != null) {
        // 调用SDK查询详细信息
        await _ringController.queryTrainingById(id);
        
        // 监听详细数据返回
        ever(_ringService.trainingDetailsRx, (details) {
          if (details != null) {
            _showExerciseDetailDialog(details);
          }
        });
      } else {
        // 如果没有ID，直接显示基本信息
        _showExerciseDetailDialog(exerciseData);
      }
    } catch (e) {
      Toast.show('查看锻炼详情失败: $e');
    }
  }
  
  /// 显示锻炼详情对话框（显示SDK返回的完整数据）
  void _showExerciseDetailDialog(Map<String, dynamic> detail) {
    // 解析时长
    final duration = detail['duration'] as int? ?? 0;
    final hours = duration ~/ 3600;
    final minutes = (duration % 3600) ~/ 60;
    final seconds = duration % 60;
    final durationText = hours > 0 
        ? '${hours}小时${minutes}分${seconds}秒'
        : '${minutes}分${seconds}秒';
    
    // 解析距离
    final distance = detail['distance'] as int? ?? 0;
    final distanceText = distance >= 1000 
        ? '${(distance / 1000).toStringAsFixed(2)} 公里'
        : '$distance 米';
    
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '锻炼详情',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 16.h),
              _buildDetailRow('运动类型', detail['type']?.toString() ?? '未知'),
              _buildDetailRow('时长', durationText),
              _buildDetailRow('距离', distanceText),
              _buildDetailRow('卡路里', '${detail['calories'] ?? 0} 千卡'),
              _buildDetailRow('平均心率', '${detail['avgHeartRate'] ?? 0} bpm'),
              _buildDetailRow('最高心率', '${detail['maxHeartRate'] ?? 0} bpm'),
              _buildDetailRow('目标达成', (detail['goalsReached'] ?? false) ? '是' : '否'),
              SizedBox(height: 20.h),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Get.back(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    padding: EdgeInsets.symmetric(vertical: 12.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                  child: Text(
                    '关闭',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  /// 构建详情行
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              color: Colors.grey[400],
              fontSize: 14.sp,
            ),
          ),
          Text(
            value,
            style: TextStyle(
              color: Colors.white,
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void onClose() {
    _gpsTimer?.cancel();
    _recordingTimer?.cancel();
    super.onClose();
  }

  /// 开始GPS信号检测
  void _startGpsSignalDetection() {
    // 模拟GPS信号强度变化
    _gpsTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      if (!state.isRecording.value) {
        // 模拟GPS信号逐渐增强
        if (state.gpsSignalStrength.value < 5) {
          state.gpsSignalStrength.value++;
        } else {
          // 信号稳定后偶尔波动
          final random = DateTime.now().millisecond % 10;
          if (random < 2) {
            state.gpsSignalStrength.value = 4;
          } else {
            state.gpsSignalStrength.value = 5;
          }
        }
      }
    });
  }

  /// 显示目标设置页面
  void showGoalSettings() {
    Get.toNamed(ExerciseRoutes.goalSetting, arguments: {
      'distance': (state.targetDistance.value / 1000).toString(),
      'time': '${(state.targetDuration.value ~/ 3600).toString().padLeft(2, '0')}:${((state.targetDuration.value % 3600) ~/ 60).toString().padLeft(2, '0')}',
      'calories': state.targetCalories.value.toString(),
      'defaultTab': 0, // 默认选中里程标签
      'exerciseName': exerciseType?.name ?? 'GPS散步', // 传递运动名称
    });
  }





  /// 居中到当前位置
  void centerMapToCurrentLocation() {
    Toast.show('正在定位到当前位置...');
    
    // TODO: 实现真实的地图定位功能
    // 这里可以集成地图SDK，如高德地图、百度地图等
  }

  /// 开始/停止记录
  void startRecording() {
    if (!state.canStartRecording) {
      Toast.show('GPS信号不足或设备未连接');
      return;
    }

    if (state.isRecording.value) {
      // 停止记录
      _stopRecording();
    } else {
      // 跳转到倒计时页面
      _goToCountdownPage();
    }
  }
  
  // ==================== SDK训练功能集成 ====================
  
  /// 查询支持的训练类型
  Future<void> querySupportTraining() async {
    try {
      await _ringController.querySupportTraining();
      Toast.show('正在查询支持的训练类型...');
    } catch (e) {
      Toast.show('查询训练类型失败: $e');
    }
  }
  
  /// 跳转到倒计时页面
  void _goToCountdownPage() {
    Get.toNamed(ExerciseRoutes.countdown, arguments: {
      'exerciseName': exerciseType?.name ?? 'GPS散步',
      'targetInfo': _getTargetInfoText(),
    });
  }
  
  /// 获取目标信息文本
  String _getTargetInfoText() {
    if (state.targetDistance.value > 0) {
      return '${(state.targetDistance.value / 1000).toStringAsFixed(2)}千米';
    } else if (state.targetDuration.value > 0) {
      final hours = state.targetDuration.value ~/ 3600;
      final minutes = (state.targetDuration.value % 3600) ~/ 60;
      if (hours > 0) {
        return '${hours}小时${minutes}分钟';
      } else {
        return '${minutes}分钟';
      }
    } else if (state.targetCalories.value > 0) {
      return '${state.targetCalories.value}千卡';
    } else {
      return '自由训练';
    }
  }

  /// 开始记录（集成SDK训练功能）
  void _startRecording() async {
    state.isRecording.value = true;
    state.isPaused.value = false;
    state.isLocked.value = false;
    state.duration.value = 0;
    state.distance.value = 0.0;
    state.calories.value = 0;
    state.steps.value = 0;

    Toast.show('${exerciseType?.name ?? 'GPS运动'}记录已开始');

    // 调用SDK开始训练
    try {
      // 将运动类型映射到SDK支持的类型
      currentTrainingType = _mapExerciseTypeToSDK(exerciseType);
      
      await _ringController.startTraining(
        type: currentTrainingType ?? '跑步',
        caloriesGoal: state.targetCalories.value > 0 ? state.targetCalories.value : null,
        durationGoal: state.targetDuration.value > 0 ? state.targetDuration.value : null,
        distanceGoal: state.targetDistance.value > 0 ? state.targetDistance.value.toInt() : null,
      );
    } catch (e) {
      Toast.show('启动SDK训练失败: $e');
    }

    // 开始计时
    _startRecordingTimer();
  }
  
  /// 将运动类型映射到SDK支持的类型
  String _mapExerciseTypeToSDK(ExerciseType? type) {
    if (type == null) return '跑步';
    
    // 根据运动类型名称映射到SDK类型
    switch (type.name) {
      case 'GPS跑步':
      case '跑步':
        return '跑步';
      case 'GPS骑行':
      case '骑行':
        return '骑行';
      case 'GPS散步':
      case '散步':
        return '散步';
      case 'GPS登山':
      case '登山':
        return '登山';
      default:
        return '跑步'; // 默认使用跑步
    }
  }

  /// 开始记录计时器
  void _startRecordingTimer() {
    _recordingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!state.isPaused.value) {
        state.duration.value++;
        
        // 模拟数据更新
        _updateRecordingData();
      }
    });
  }

  /// 停止记录（集成SDK）
  void _stopRecording() async {
    state.isRecording.value = false;
    state.isPaused.value = false;
    state.isLocked.value = false;
    _recordingTimer?.cancel();

    // 调用SDK结束训练
    try {
      await _ringController.endTraining();
      
      // 等待一下让SDK保存数据
      await Future.delayed(const Duration(seconds: 1));
      
      // 重新加载锻炼列表以显示刚完成的训练
      await loadExerciseList();
    } catch (e) {
      Toast.show('结束SDK训练失败: $e');
    }

    // 显示运动总结
    _showExerciseSummary();
  }

  /// 更新记录数据
  void _updateRecordingData() {
    // 模拟数据更新
    final duration = state.duration.value;
    
    // 模拟距离增加（假设平均速度5km/h）
    state.distance.value = (duration * 5000 / 3600); // 米
    
    // 模拟速度变化
    state.currentSpeed.value = 4.5 + (DateTime.now().millisecond % 20) * 0.1;
    state.averageSpeed.value = state.distance.value / duration * 3.6; // km/h
    
    // 模拟卡路里消耗（基于运动类型和时间）
    final caloriesPerMinute = exerciseType?.caloriesPerMinute ?? 5.0;
    state.calories.value = (duration * caloriesPerMinute / 60).round();
    
    // 模拟步数（假设每分钟100步）
    state.steps.value = (duration * 100 / 60).round();
  }

  /// 显示运动总结
  void _showExerciseSummary() {
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.grey[900],
        title: Text(
          '运动完成',
          style: TextStyle(color: Colors.white, fontSize: 18.sp),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildSummaryItem('运动时长', '${state.duration.value ~/ 60}分${state.duration.value % 60}秒'),
            _buildSummaryItem('运动距离', '${(state.distance.value / 1000).toStringAsFixed(2)} 公里'),
            _buildSummaryItem('消耗卡路里', '${state.calories.value} 千卡'),
            _buildSummaryItem('步数', '${state.steps.value} 步'),
            _buildSummaryItem('平均速度', '${state.averageSpeed.value.toStringAsFixed(1)} km/h'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
              Get.back(); // 返回到锻炼选择页面
            },
            child: Text('完成', style: TextStyle(color: Colors.orange)),
          ),
        ],
      ),
    );
  }

  /// 构建总结项
  Widget _buildSummaryItem(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(color: Colors.grey[400], fontSize: 14.sp),
          ),
          Text(
            value,
            style: TextStyle(color: Colors.white, fontSize: 14.sp, fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }
  
  /// 切换锁定状态
  void toggleLock() {
    if (state.isLocked.value) {
      // 如果当前是锁定状态，点击"结束"按钮
      _showStopConfirmDialog();
    } else {
      // 锁定屏幕
      state.isLocked.value = true;
      Toast.show('屏幕已锁定，防止误触，点击结束按钮可解锁并结束运动');
    }
  }

  
  
  /// 切换暂停状态
  void togglePause() {
    if (state.isPaused.value) {
      // 继续运动
      state.isPaused.value = false;
      _resumeRecording();
    } else {
      // 暂停运动
      state.isPaused.value = true;
      _pauseRecording();
    }
  }
  
  /// 暂停记录（集成SDK）
  void _pauseRecording() async {
    _recordingTimer?.cancel();
    
    // 调用SDK暂停训练
    try {
      await _ringController.pauseTraining();
    } catch (e) {
      Toast.show('暂停SDK训练失败: $e');
    }
    
    Toast.show('运动已暂停，点击继续按钮恢复运动记录');
  }
  
  /// 恢复记录（集成SDK）
  void _resumeRecording() async {
    // 调用SDK继续训练
    try {
      await _ringController.resumeTraining();
    } catch (e) {
      Toast.show('恢复SDK训练失败: $e');
    }
    
    _startRecordingTimer();
    Toast.show('运动已恢复，继续记录您的运动数据');
  }
  
  /// 显示停止确认对话框
  void _showStopConfirmDialog() {
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.grey[900],
        title: const Text(
          '结束运动',
          style: TextStyle(color: Colors.white),
        ),
        content: const Text(
          '确定要结束这次运动吗？运动数据将被保存。',
          style: TextStyle(color: Colors.grey),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text(
              '取消',
              style: TextStyle(color: Colors.grey),
            ),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              _stopRecording();
            },
            child: const Text(
              '结束',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }
}
